<!-- 发日常贴 -->
<template>
  <view class="content">
    <form @submit="formSubmit" @reset="formReset" style="position: absolute; top: 10%; width: 350px;">
      <div> <!-- 帖子类型 -->
        <label><text>帖子类型：</text></label>
        <picker @change="handlePickerChange" :value="index" :range="kindList" range-key="name">
          <view class="picker">
            {{ kindList[index].name }}
          </view>
        </picker>
      </div>
      <div> <!-- 内容 -->
        <textarea v-model="e_content" name="content" placeholder="请输入内容:" maxlength="300" cols="100"
          rows="200"></textarea>
      </div>
      <!-- 上传图片 -->
      <div style="width: 350px;">
        <button @click="chooseImage()" style="">上传图片（至多六张）</button>
        <image v-for="(url, index) in imageUrls" :src="url" :key="index" style="height: 80px;width: 80px;">
        </image>
      </div>
      <div>
        <button form-type="submit">发布</button>
        <button type="default" form-type="reset">重置</button>
      </div>
    </form>
  </view>
</template>

<script>
  // 引入请求方法
  import {
    reqPublishDailyBlog,
    reqUploadPicture
  } from '@/api/post/daily';

  export default {
    data() {
      return {
        e_content: '',
        kindList: [{
            name: "日常分享",
            id: 1
          },
          {
            name: "技能提升",
            id: 2
          },
          {
            name: "吐槽",
            id: 3
          }
        ],
        index: 0,
        imageUrls: [], // 存储已选择的图片路径
        formimageUrls: '', //随表单上传的字符串
        imageCount: 0, //待上传图片数量
      };
    },
    methods: {
      handlePickerChange: function(e) { //更新选择器下标
        this.index = e.detail.value;
      },

      async formSubmit() {
        getApp().globalData.blogType = this.index //获取当前选择类型下标（全局变量）
        var formData = {
          content: this.e_content,
          images: this.formimageUrls
        };
        var jsonData = JSON.stringify(formData); //将表单数据转换成json类型数据

        wx.showLoading({
          title: '发布中ing',
          icon: 'loading',
          mask: true,
          duration: 100000,
        });

        let result = await reqPublishDailyBlog(getApp().globalData.blogType, jsonData);
        wx.hideLoading()
        if (result.success) {
          wx.showToast({
            title: '发布成功',
            icon: 'success',
            mask: true,
            duration: 1500,
            success: function() {
              setTimeout(function() {
                wx.navigateBack()
              }, 1500);
            }
          })
        } else {
          wx.showToast({
            title: '发布失败',
            icon: 'error',
            mask: true,
            duration: 1500,
          })
        }
      },

      formReset: function(e) {
        console.log('清空数据')
      },

      chooseImage() {
        uni.chooseImage({
          count: 6, // 可以选择的图片数量
          success: (res) => {
            this.imageUrls = res.tempFilePaths; // 将选择的图片路径保存起来
            this.imageCount = this.imageUrls.length
            this.uploadImages()
          },
          fail: (err) => {
            console.log(err);
          },
        });
      },

      async uploadImages() {
        wx.showLoading({
          title: '上传图片中...',
          icon: 'loading',
          mask: true,
          duration: 100000,
        })

        for (const path of this.imageUrls) {
          try {
            let result = await reqUploadPicture(path);
            if (result) {
              console.log('图片上传成功' + result);
              if (this.formimageUrls == '') {
                this.formimageUrls = this.formimageUrls.concat(result);
              } else {
                this.formimageUrls = this.formimageUrls.concat(',' + result);
              }
              this.imageCount--;
              if (this.imageCount == 0) {
                wx.hideLoading();
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1500,
                  mask: true
                });
              }
            } else {
              console.log('图片上传失败');
            }
          } catch (error) {
            console.log('图片上传失败', error);
          }
        }
        wx.hideLoading()
      },
    }
  }
</script>

<style>
  page {
    height: 100vh;
    width: 100vw;
  }

  .back_button {
    position: absolute;
    border: none !important;
    border-color: transparent;
    right: 0%;
    top: 0%;
  }

  picker {
    display: inline-block;
    vertical-align: middle;
    z-index: 9999;
    /* 最上层 */
    width: 200px;
    height: 30px;
    line-height: 30px;
    border: 1px solid #acacac;
    border-radius: 4px;
    text-align: center;
    background-color: #ffffff;
    margin-bottom: 15px;
    margin-left: 15px;
  }

  label {
    border: 1px solid #acacac;
    border-radius: 4px;
    background-color: #ffffff;
    height: 30px;
    width: 80px;
    text-align: center;
  }

  textarea {
    border: 1px solid #acacac;
    border-radius: 10px;
    display: inline-block;
    vertical-align: top;
    margin-left: 5px;
    background-color: #ffffff;
    height: 300px;
  }

  button {
    background-color: #00aa00;
    color: white;
    padding: 5px 15px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    width: 220px;
    /* 设置按钮宽度 */
    height: 55px;
    /* 设置按钮高度 */
    margin-top: 10px;
  }

  .content {
    background-image: url();
    /* 图片素材background_2.jpg */
    background-size: cover;
    height: 100vh;
    width: 100vw;

    display: flex;
    /* 弹性布局 */
    flex-direction: column;
    /* 设置从上往下布局 */
    align-items: center;
    /* 水平居中 */
    justify-content: center;
    /* 垂直居中 */
  }
</style>